package com.smart.common.annotation;


import cn.hutool.core.util.ObjectUtil;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

/**
 * 枚举校验器
 *
 * @author 夏绪秋
 * @date 2022-09-27
 */
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValidator.Validator.class)

public @interface EnumValidator {

    String message() default "{EnumValueValidator's value is invalid}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<? extends Enum<?>> cls();

    class Validator implements ConstraintValidator<EnumValidator, Object> {

        private Class<? extends Enum<?>> enumClass;


        @Override
        public void initialize(EnumValidator enumValue) {
            enumClass = enumValue.cls();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null) {
                return Boolean.TRUE;
            }

            try {
                //定义一个枚举方法名
                Enum<?>[] enumConstants = enumClass.getEnumConstants();
                Method getValue = enumClass.getMethod( "getValue" );
                for (Enum enum1 : enumConstants) {
                    Object enumValue = getValue.invoke( enum1 );
                    if (ObjectUtil.equals( value, enumValue )) {
                        return Boolean.TRUE;
                    }


                }
                return Boolean.FALSE;
            } catch (Exception e) {
                e.printStackTrace();
                return Boolean.FALSE;
            }

        }

    }
}